package {
	import com.jfdesgagne.traklib.Traklib;
	import com.jfdesgagne.traklib.events.TrakEvent;
	import com.jfdesgagne.traklib.events.TrakMultiEvent;
	import com.jfdesgagne.traklib.statics.TrakTypes;
	import com.jfdesgagne.traklib.ui.elements.TrakUICursor;
	import com.jfdesgagne.traklib.utils.FPS;

	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.geom.Rectangle;

	/**
	 * @author jdesgagne
	 */
	public class Main extends Sprite {
		protected var __tracklib:Traklib;
		protected var __trakCursor:TrakUICursor;
		protected var __FPS:FPS;
		protected var __cursors:Array = [];

		public function Main() {
			//Setup stage
			this.stage.align = StageAlign.TOP_LEFT;
			
			//Init Tracklib + elements
			this.initTraklib();
			this.initCursor();			this.initFPS();
		}

		protected function initTraklib():void {
			this.__tracklib = new Traklib(this);
			this.__tracklib.trackingType = TrakTypes.COLOR_TRACKING;
			this.__tracklib.showInterace(true);
			this.__tracklib.debug = true;
			this.__tracklib.addEventListener(TrakEvent.MOVE, this.moveCursor);//			this.__tracklib.addEventListener(TrakMultiEvent.CREATE, this.createNewCursor);//			this.__tracklib.addEventListener(TrakMultiEvent.DISAPPEAR, this.destroyCursor);//			this.__tracklib.addEventListener(TrakMultiEvent.MOVE, this.moveMultiCursor);
		}

		protected function initFPS():void {
			this.__FPS = new FPS();
			this.addChild(this.__FPS);
		}

		protected function initCursor():void {
			this.__trakCursor = new TrakUICursor();
			this.addChild(this.__trakCursor);
		}
		
		protected function createNewCursor(e:TrakMultiEvent):void {
			this.__cursors[e.id] = new TrakUICursor();
			this.addChild(this.__cursors[e.id]);
		}
		
		protected function destroyCursor(e:TrakMultiEvent):void {
			if(this.__cursors[e.id]) {
				TrakUICursor(this.__cursors[e.id]).destroy();
				this.removeChild(this.__cursors[e.id]);
				this.__cursors[e.id] = null;
			}
		}
		
	
		protected function moveCursor(e:TrakEvent):void {
			var area:Rectangle = new Rectangle(e.area.x + e.area.width / 2, e.area.y + e.area.height / 2, e.area.width, e.area.height);
			this.__trakCursor.move(area);
			if(this.__tracklib.distance) {
				this.__trakCursor.grow(area);
			} else {
				this.__trakCursor.grow(null);
			}
		}
		 
		 protected function moveMultiCursor(e:TrakMultiEvent):void {
		 	var area:Rectangle = new Rectangle(e.area.x + e.area.width / 2, e.area.y + e.area.height / 2, e.area.width, e.area.height);
			TrakUICursor(this.__cursors[e.id]).move(area);
			if(this.__cursors[e.id].distance) {
				this.__cursors[e.id].grow(area);
			} else {
				this.__cursors[e.id].grow(null);
			}
		}
	}
}
